<?php

namespace App\Http\Controllers\Admin;

use App\Handler\ImageHandler;
use App\Http\Requests\Admin\ArticleRequest;
use App\Models\Article;
use App\Models\Category;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ArticleController extends Controller
{
	use ImageHandler;
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Article $articleModel)
    {
    	/*$text = '1234567';
		if($text){
			//打开文件
			$file = 'd.txt';
			//定义文件数组
			$fileArr = [];

			$fileHandler = fopen($file,'a+');

			while (!feof($fileHandler)){
				$fileArr[] = str_replace("\r\n", '', fgets($fileHandler));
			}

			//清空文件
			file_put_contents($file,"");
			//把内容的顶行清除
			if($fileArr){
				unset($fileArr['0']);
			}
			//把text进行追加到数组
			$fileArr[] = $text;

			//写入文件
			foreach ($fileArr as $k => $v) {
				fwrite($fileHandler,$v);
				
				if($v != end($fileArr)){
					fwrite($fileHandler,"\r\n");
				}
			}
			//关闭文件

			fclose($fileHandler);
		}*/
//    	$list = \DB::table('category')->get()->toArray();
//    	var_dump($list);
//
//    	$category = Category::all()->where('pid','=',0)->toArray();
//
//		var_dump($category);
//
//    	foreach ($category as $k => $v) {
//    		$second = Category::all()->where('pid','=',$v['id'])->toArray();
//    			foreach ($second as $k1 => $v1) {
//    			    $second[$k1]['child'] = Category::all()->where('pid','=',$v1['id'])->toArray();
//    			}
//    		$category[$k]['child'] = $second;
//			$category[$k]['child']= Category::all()->where('pid','=',$v['id'])->toArray();
//    	}
//    	
//    	echo '<pre>';
//    	var_dump($category);
//    	die;

    	$articleList = $articleModel->with(['category'])
					->orderBy('id','desc')
					->paginate(10);

        return view('admin.article.index',compact('articleList'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
    	$categoryList = Category::all()->toArray();
    	$categoryList = getTree($categoryList);

        return view('admin.article.create',compact('categoryList'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(ArticleRequest $request,Article $articleModel)
    {
		if($request->method() == 'POST'){
			//接受数据
			$articleData = $request->except(['_token','thumb','tag']);

			//判断是否有文件
			if($request->hasFile('thumb')){

				$uploadImage = $this->imageUploader('uploads/article','thumb');

				if($uploadImage['status'] == '200'){
					$articleData['thumb'] = $uploadImage['path'];
				}else{
					return back()->with('danger',$uploadImage['msg']);
				}
			}

			//用fill方法才会自动维护时间自动 更新也如此
			$articleModel->fill($articleData);
			$articleModel->admin_id = \Auth::id();

			$articleModel->save($articleData);

			//获得文章的tag数组
			$tag_ids = $articleModel->getTagIds();

			if($tag_ids){
				//写入到关联表
				$articleModel->tag()->attach($tag_ids);
			}

			return redirect()->route('admin.article.index')->with('success','添加成功');
		}
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
		$categoryList = Category::all()->toArray();
		$categoryList = getTree($categoryList);

        $article = Article::findOrfail($id);

        $article_tags = '';

        if($article){
            $article_tags = $article->tag->toArray();

			if($article_tags){
				$article_tags = implode(',',array_column($article_tags,'tag_name'));
			}else{
				$article_tags = '';
			}
        }
        
        return view('admin.article.edit',compact('article','article_tags','categoryList'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(ArticleRequest $request, Article $articleModel,$id)
    {
        if(\request()->method() == 'POST'){
        	$article = Article::findOrFail($id);

        	$articleData = $request->except(['_token','thumb','tags']);
        	
        	//判断图片
			if($request->hasFile('thumb')){
			    $uploadImg = $this->imageUploader('uploads/article','thumb');
			    if($uploadImg['status'] == 200){
			        $articleData['thumb'] = $uploadImg['path'];

			        //删除原图
					@unlink( public_path() . '/' . $article->thumb);
			    }else{
			    	return back()->with('info',$uploadImg['msg']);
				}
			}

			//编辑的时候判断是否有 is_show 没有的话表示是关闭显示了
			if(!isset($articleData['is_show'])){
				$article->is_show = 0;
			}

			$article->fill($articleData);
			$article->update();

			//判断tags
			$tags_ids = $articleModel->getTagIds();

			//如果有 就更新tags
			if($tags_ids){
				$article->tag()->detach();
				$article->tag()->attach($tags_ids);
			}else{
				//没有tags 就直接清空
				$article->tag()->detach();
			}

			return redirect()->route('admin.article.index')->with('success','更新成功');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $article = Article::findOrfail($id);
        $article->delete();

        return back()->with('success','删除成功');
    }
}
